<template>
  <div class="template-renderer">
    <div class="line" ref="lineRef"></div>
    <button class="copy-line-btn" @click="copyLine" v-if="showCopyButton">
      📋 复制本段
    </button>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, onMounted, nextTick } from 'vue';

// Props
interface Props {
  template: string; // 模板字符串
  data: Record<string, any>; // 数据对象
  showCopyButton?: boolean; // 是否显示复制按钮
}

const props = withDefaults(defineProps<Props>(), {
  showCopyButton: true
});

// Emits
const emit = defineEmits<{
  'update:data': [data: Record<string, any>];
}>();

// Refs
const lineRef = ref<HTMLElement>();

// 创建canvas用于测量文本宽度
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');

// 测量文本宽度的函数
function measureText(text: string): number {
  if (!ctx) return 0;
  ctx.font = '18px sans-serif';
  return ctx.measureText(text || ' ').width + 8;
}

// 渲染模板
async function renderTemplate() {
  await nextTick();
  if (!lineRef.value) return;

  // 简单的模板渲染实现
  let html = props.template;
  
  // 替换 {{ }} 中的变量
  html = html.replace(/\{\{\s*([^}]+?)\s*\}\}/g, (_, key) => {
    return props.data[key.trim()] || '';
  });

  // 处理条件判断（简化版，实际项目中可使用更完善的模板引擎）
  const ifRegex = /\{%\s*if\s+([^}]+?)\s*%\}([\s\S]*?)\{%\s*endif\s*%\}/g;
  html = html.replace(ifRegex, (_, condition, content) => {
    const conditionKey = condition.trim();
    return props.data[conditionKey] ? content : '';
  });

  // 设置内容
  lineRef.value.innerHTML = html;

  // 处理输入框
  const inputSpans = lineRef.value.querySelectorAll('.njk-input');
  inputSpans.forEach(span => {
    const placeholder = span.getAttribute('data-placeholder') || '';
    const input = document.createElement('input');
    input.type = 'text';
    input.placeholder = placeholder;
    input.value = span.textContent || '';
    input.style.width = `${measureText(placeholder)}px`;

    // 输入事件处理
    input.addEventListener('input', (e) => {
      const target = e.target as HTMLInputElement;
      span.textContent = target.value;
      
      // 根据placeholder确定要更新的数据字段
      let fieldName = '';
      if (placeholder.includes('林地')) fieldName = '林地面积';
      else if (placeholder.includes('耕地')) fieldName = '耕地面积';
      else if (placeholder.includes('永农')) fieldName = '永农面积';
      else if (placeholder.includes('审查机关')) fieldName = '审查机关';
      
      if (fieldName) {
        const newData = { ...props.data, [fieldName]: target.value };
        emit('update:data', newData);
      }
      
      // 调整输入框宽度
      target.style.width = `${measureText(target.value || placeholder)}px`;
    });

    span.replaceWith(input);
  });
}

// 复制当前行内容，确保包含输入框中的最新内容
function copyLine() {
  if (!lineRef.value) return;
  
  // 创建一个临时元素来获取完整文本内容
  const tempDiv = document.createElement('div');
  tempDiv.innerHTML = lineRef.value.innerHTML;
  
  // 替换所有输入框为它们的当前值
  const inputs = tempDiv.querySelectorAll('input');
  inputs.forEach(input => {
    const textNode = document.createTextNode(input.value || '');
    input.parentNode?.replaceChild(textNode, input);
  });
  
  const text = tempDiv.textContent?.trim() || '';
  if (!text) return;

  // 复制到剪贴板
  if (navigator.clipboard) {
    navigator.clipboard.writeText(text).then(showCopiedTip);
  } else {
    const textarea = document.createElement('textarea');
    textarea.value = text;
    textarea.style.position = 'fixed';
    textarea.style.opacity = '0';
    document.body.appendChild(textarea);
    textarea.select();
    document.execCommand('copy');
    document.body.removeChild(textarea);
    showCopiedTip();
  }
}

// 显示复制成功提示
function showCopiedTip() {
  // 创建或使用现有的提示元素
  let tip = document.getElementById('copied-tip');
  if (!tip) {
    tip = document.createElement('div');
    tip.id = 'copied-tip';
    tip.className = 'copied';
    tip.textContent = '已复制到剪贴板！';
    tip.style.cssText = `
      position: fixed;
      top: 20px;
      left: 50%;
      transform: translateX(-50%);
      background: #323232;
      color: #fff;
      padding: 0.6rem 1.2rem;
      border-radius: 4px;
      z-index: 1000;
      display: none;
    `;
    document.body.appendChild(tip);
  }

  tip.style.display = 'block';
  setTimeout(() => {
    tip.style.display = 'none';
  }, 1500);
}

// 监听属性变化，重新渲染
watch(
  () => [props.template, props.data],
  () => renderTemplate(),
  { deep: true }
);

// 组件挂载后渲染
onMounted(() => {
  renderTemplate();
});
</script>

<style scoped>
.template-renderer {
  margin-bottom: 1rem;
}

.line {
  margin: 0.6rem 0;
  font-size: 18px;
}

.line input {
  border: none;
  border-bottom: 1px solid #000;
  text-align: center;
  font-size: 18px;
  padding: 2px 4px;
  min-width: 3rem;
}

.copy-line-btn {
  margin-left: 0.8rem;
  background: #607d8f;
  color: #fff;
  border: none;
  padding: 0.4rem 0.8rem;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.copy-line-btn:hover {
  background: #455a64;
}

.copy-line-btn:active {
  transform: scale(0.98);
}
</style>